package com.sa35.fbs.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sa35.fbs.form.LoginForm;
import com.sa35.fbs.model.UserRoleEnum;
import com.sa35.fbs.service.UserService;
import com.sa35.fbs.vo.UserVO;

@Controller
public class LoginController extends BaseController {

	@Autowired
	UserService userService;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String getLogin(HttpServletRequest request, Map model) {
		if(getSessionUser(request)!=null){
			return "redirect:/";
		}
		LoginForm loginForm = new LoginForm();
		model.put("loginForm", loginForm);
		return "login";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@Valid LoginForm loginForm, BindingResult result,
			Map model,HttpServletRequest request) {
		UserVO userVO = userService.auth(loginForm);
		if(userVO == null){
			result.rejectValue("password","","login failed");
		}else{
			setSessionUser(request, userVO);
			return "redirect:/";
		}
		return "login";
	}

	@RequestMapping(value="logout", method=RequestMethod.GET)
	public String logout(HttpServletRequest request){
		request.getSession().removeAttribute("fbs_user");
		return "redirect:/";
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
